package com.tubeonfire.model.admin;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;
import com.tubeonfire.entity.Page;

public class PageModel {
	private static final Logger log = Logger.getLogger(PageModel.class
			.getName());

	private static Objectify ofy;

	private static Cache cache = null;

	private static boolean isRegisted = false;

	private static ObjectifyOpts opts = null;

	private static String cachePrefix = "PageModel_";

	private List<Page> listResult = new ArrayList<Page>();

	public List<Page> getListResult() {
		return listResult;
	}

	public void setListResult(List<Page> listResult) {
		this.listResult = listResult;
	}

	public static void init() {
		if (!isRegisted) {
			isRegisted = true;
			try {
				ObjectifyService.register(Page.class);
			} catch (Exception e) {
				isRegisted = false;
			}
			try {
				cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
			} catch (CacheException e) {
				isRegisted = false;
			}
			opts = new ObjectifyOpts().setSessionCache(true);
		}
		ofy = ObjectifyService.begin(opts);
	}

	public PageModel() {
		init();
	}

	@SuppressWarnings("unchecked")
	public static void insert(Page obj) {
		init();
		if (cache != null) {
			String prefix = cachePrefix + "id_" + obj.getId();
			cache.put(prefix, obj);
		}
		ofy.put(obj);
	}

	public static void delete(Page obj) {
		init();
		String prefix = cachePrefix + "id_" + obj.getId();
		if (cache != null && cache.containsKey(prefix)) {
			cache.remove(prefix);
		}
		ofy.delete(obj);
	}

	@SuppressWarnings("unchecked")
	public static Page getById(String id) {
		try {
			init();
			Page obj = new Page();
			String prefix = cachePrefix + "id_" + id;
			if (cache != null && cache.containsKey(prefix)) {
				obj = (Page) cache.get(prefix);
			} else {
				try {
					obj = ofy.get(new Key<Page>(Page.class, id));
					cache.put(prefix, obj);
				} catch (Exception e) {
					obj = null;
				}
			}
			return obj;
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			return null;
		}
	}

	public void prepareList() {
		try {
			listResult = new ArrayList<Page>();
			Query<Page> q = ofy.query(Page.class).order("-updated");
			for (Page obj : q) {
				listResult.add(obj);
			}
		} catch (Exception e) {
			log.warning(e.toString());
			e.printStackTrace();
			listResult = new ArrayList<Page>();
		}
	}
}
